<script setup lang="ts">
import { onMounted, reactive } from 'vue'
import {
  ElSpace,
  ElTable,
  ElTableColumn,
  ElForm,
  ElFormItem,
  ElButton,
  ElInput,
  ElCheckbox,
  ElDatePicker,
  ElSelect,
  ElOption,
  ElMessage,
  ElPagination,
  ElMessageBox
} from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { useIcon } from '@/hooks/web/useIcon'
import {
  RetrieveIndex,
  UpdateIndex,
  CreateIndex,
  RetrieveIndexDetail,
  UpdateIndexDetail,
  BrushIndexDetail,
  CreateIndexDetail,
  RetrieveIndexExist
} from '@/api/syscontent/datlib'
import { formatToDate } from '@/utils/dateUtil'
import {
  IndexDataType,
  EditIndexParams,
  IndexItem,
  ManageIndexParams,
  IndexValue
} from './types/dataindex'

const plusIcon = useIcon({ icon: 'system-uicons:plus' })

const indexData = reactive<IndexDataType>({
  kw: '',
  rows: [],
  page: 1,
  page_size: 30,
  totalRows: 0
})
const dialogParams = reactive<EditIndexParams>({
  isShow: false,
  showTitle: '',
  confirmButtonText: '确定创建',
  saveLoading: false,
  frequencyList: ['日', '周', '月', '季', '年']
})
const detailDailog = reactive<ManageIndexParams>({
  indexId: -1,
  isShow: false,
  title: '管理数据',
  dataLoading: false,
  page: 1,
  pageSize: 50,
  totalCount: 0,
  valueList: [],
  showCreateNew: false,
  newCreateLoading: false,
  newDatadate: formatToDate(new Date()),
  newDatavalue: undefined,
  createTime: '',
  updateTime: ''
})

const initIndexItem = {
  iid: -1,
  name: '',
  plat: '',
  plat_id: '',
  frequency: '',
  unit: '',
  start_date: '',
  source: '',
  note: '',
  state: false,
  is_active: false
}

const editIndex = reactive<IndexItem>(JSON.parse(JSON.stringify(initIndexItem)))

const tablePageChange = (p: number) => {
  indexData.page = p
  loadIndexRows()
}
const diagTablePageChange = (p: number) => {
  detailDailog.page = p
  loadIndexDetail()
}

const toShowEditIndexDiag = (row: IndexItem) => {
  // console.log(row)
  Object.assign(editIndex, row)
  editIndex.index_id = row.id
  dialogParams.showTitle = '编辑指标信息'
  dialogParams.confirmButtonText = '确定保存'
  dialogParams.isShow = true
}

const toManageIndexData = (row: IndexItem) => {
  // console.log(row)
  if (!row.id) return
  detailDailog.indexId = row.id
  detailDailog.title = row.name
  detailDailog.isShow = true
  detailDailog.createTime = row.create_time
  detailDailog.updateTime = row.update_time
  loadIndexDetail()
}

// 获取指标详细数据
const loadIndexDetail = () => {
  const parm = {
    index_id: detailDailog.indexId,
    page: detailDailog.page,
    page_size: detailDailog.pageSize
  }
  detailDailog.dataLoading = true
  RetrieveIndexDetail(parm).then((res) => {
    // console.log(res)
    detailDailog.valueList = res.data.rows.map((item: any) => {
      item.isEditing = false
      return item
    })
    detailDailog.totalCount = res.data.total_count
    detailDailog.dataLoading = false
  })
}
// 新增数据行
const toSaveNewRow = () => {
  if (Number.isNaN(parseFloat(detailDailog.newDatavalue + ''))) {
    ElMessage.error('请输入正确的数值!')
    return
  }

  const newRow = {
    datadate: detailDailog.newDatadate,
    datavalue: detailDailog.newDatavalue
  }
  detailDailog.newCreateLoading = true
  CreateIndexDetail(detailDailog.indexId, [newRow])
    .then((res) => {
      ElMessage.success(res.message)
      detailDailog.newCreateLoading = false
      detailDailog.showCreateNew = false
      loadIndexDetail()
    })
    .catch(() => {
      detailDailog.newCreateLoading = false
    })
}
// 修改数据行
const toEditValueRow = (row: IndexValue) => {
  // console.log(row)
  row.isEditing = !row.isEditing
}
// 保存数据行
const toSaveEditValueRow = (row: IndexValue) => {
  row.rid = row.id
  UpdateIndexDetail(detailDailog.indexId, [row]).then(() => {
    ElMessage.success('修改成功!')
    row.isEditing = false
    loadIndexDetail()
  })
}
// 删除数据行 row: IndexValue
const toDeleteValueRow = () => {
  // console.log(row)
  ElMessage.error('暂不支持单条删除!')
}
// 清空所有数据
const toBrushIndexDetail = () => {
  ElMessageBox({
    title: '警告',
    message: '确定清空所有数据吗?操作不可恢复!',
    type: 'warning',
    showCancelButton: true
  })
    .then(() => {
      BrushIndexDetail(detailDailog.indexId).then((res) => {
        ElMessage.success(res.message)
        loadIndexDetail()
      })
    })
    .catch(() => {})
}

const toShowCreateIndexDiag = () => {
  Object.assign(editIndex, initIndexItem)
  editIndex.index_id = -1
  dialogParams.showTitle = '新建指标'
  dialogParams.confirmButtonText = '确定创建'
  dialogParams.isShow = true
}
const toSaveIndexRow = async () => {
  dialogParams.saveLoading = true
  let resData: any = null
  try {
    if (editIndex.index_id && editIndex.index_id > 0) {
      resData = await UpdateIndex(editIndex) // 修改
    } else {
      resData = await CreateIndex(editIndex) // 新建
    }
  } catch (error) {
    dialogParams.saveLoading = false
  }
  if (resData) {
    ElMessage.success({ message: resData.message })
    dialogParams.saveLoading = false
    dialogParams.isShow = false
    loadIndexRows()
  }
}

const platIdBlurEvent = async (_: any, value: any, callback: any) => {
  if (value === '' && editIndex.plat.length > 0) {
    callback(new Error('请输入平台ID'))
  } else {
    const retData: any = await RetrieveIndexExist(editIndex.plat, editIndex.plat_id)
    if (retData.data.exist) {
      callback(new Error('该指标已存在，不用重复添加！'))
    } else {
      callback()
    }
  }
}

const createIndexFormRules: any = reactive({
  platid: [{ validator: platIdBlurEvent, trigger: 'blur' }]
})

const loadIndexRows = () => {
  RetrieveIndex({
    kw: indexData.kw,
    page: indexData.page,
    page_size: indexData.page_size
  }).then((res) => {
    const retData = res.data.data
    indexData.rows = retData.rows
    indexData.totalRows = retData.total_count
  })
}

const toLoadIndexRows = () => {
  indexData.page = 1
  indexData.totalRows = 0
  indexData.rows = []
  loadIndexRows()
}

onMounted(() => {
  loadIndexRows()
})
</script>
<template>
  <div class="page-view">
    <div class="actions-box">
      <ElInput
        v-model="indexData.kw"
        clearable
        placeholder="输入平台ID或名称关键字查询"
        style="margin-right: 10px"
        @change="toLoadIndexRows"
      />
      <ElButton type="primary" :icon="plusIcon" @click="toShowCreateIndexDiag">新建</ElButton>
    </div>
    <ElTable class="table" border stripe :data="indexData.rows">
      <ElTableColumn prop="id" label="ID" width="100">
        <template #default="scope">
          <div class="edit-column" @click="toShowEditIndexDiag(scope.row)">
            <Icon class="edit-icon" icon="svg-icon:box-edit" />
            <div class="row-id">{{ scope.row.id }}</div>
          </div>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="name" label="名称" show-overflow-tooltip>
        <template #default="scope">
          <div class="index-name">
            {{ scope.row.name }}
            <span class="action" @click="toManageIndexData(scope.row)">数据管理</span>
          </div>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="end_value" label="最新值" width="125" />
      <ElTableColumn prop="unit" label="单位" width="100" />
      <ElTableColumn prop="plat_id" label="平台ID" width="150" />
      <ElTableColumn prop="db_name" label="数据库名" width="110" />
      <ElTableColumn prop="tb_name" label="数据表名" align="right" width="180" />
      <ElTableColumn prop="start_date" label="开始日期" width="120" />
      <ElTableColumn prop="end_date" label="结束日期" width="110" />
      <ElTableColumn prop="frequency" label="频率" width="70" />
      <ElTableColumn label="有效" width="70" align="center">
        <template #default="scope">
          <Icon v-if="scope.row.is_active" icon="svg-icon:dash-yes" />
        </template>
      </ElTableColumn>
    </ElTable>
    <div class="page-box">
      <ElPagination
        v-model:current-page="indexData.page"
        v-model:page-size="indexData.page_size"
        hide-on-single-page
        background
        small
        layout="total,prev,pager,next,jumper"
        :total="indexData.totalRows"
        @current-change="tablePageChange"
      />
    </div>
    <!-- 编辑指标 -->
    <Dialog v-model="dialogParams.isShow" :title="dialogParams.showTitle">
      <ElForm label-position="right" label-width="70" :rules="createIndexFormRules">
        <ElFormItem label="数据名称">
          <ElInput v-model="editIndex.name" placeholder="数据指标的名称" />
        </ElFormItem>
        <ElFormItem label="所在平台">
          <ElSelect
            v-model="editIndex.plat"
            style="width: 100%"
            :disabled="editIndex.index_id ? editIndex.index_id > 0 : false"
          >
            <ElOption value="ruizhi" label="系统自建" />
            <ElOption value="ths" label="同花顺" />
            <ElOption value="wind" label="万得" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="平台ID" prop="platid">
          <ElInput
            v-model="editIndex.plat_id"
            placeholder="数据所在平台的ID,自建时不填"
            :disabled="
              (editIndex.index_id ? editIndex.index_id > 0 : false) || editIndex.plat === 'ruizhi'
            "
          />
        </ElFormItem>
        <ElFormItem label="数据频率">
          <ElSelect v-model="editIndex.frequency" style="width: 100%">
            <ElOption v-for="f in dialogParams.frequencyList" :key="f" :value="f" :label="f" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="数据单位">
          <ElInput v-model="editIndex.unit" placeholder="数据指标的单位" />
        </ElFormItem>
        <ElFormItem label="开始日期">
          <ElDatePicker
            v-model="editIndex.start_date"
            value-format="YYYY-MM-DD"
            style="width: 100%"
            placeholder="数据指标的开始日期(必选)"
          />
        </ElFormItem>
        <ElFormItem label="数据来源">
          <ElInput v-model="editIndex.source" placeholder="数据指标的原始来源信息" />
        </ElFormItem>
        <ElFormItem label="备注信息">
          <ElInput v-model="editIndex.note" placeholder="备注信息" />
        </ElFormItem>
        <ElFormItem label="是否停更">
          <ElCheckbox v-model="editIndex.state">是</ElCheckbox>
        </ElFormItem>
        <ElFormItem label="是否有效">
          <ElCheckbox v-model="editIndex.is_active">是</ElCheckbox>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="dialogParams.isShow = false">关闭</ElButton>
        <ElButton @click="toSaveIndexRow" :loading="dialogParams.saveLoading" type="primary">
          {{ dialogParams.confirmButtonText }}
        </ElButton>
      </template>
    </Dialog>
    <!-- 管理数据 -->
    <Dialog v-model="detailDailog.isShow">
      <template #title>
        <div class="title-box">
          <div class="title-name">{{ detailDailog.title }}</div>
          <ElButton type="danger" link @click="toBrushIndexDetail">清空</ElButton>
          <ElButton
            type="primary"
            link
            style="margin-right: 10px"
            @click="detailDailog.showCreateNew = true"
            >新增</ElButton
          >
          <div v-show="detailDailog.showCreateNew" class="new-value">
            <ElSpace>
              <ElDatePicker
                v-model="detailDailog.newDatadate"
                value-format="YYYY-MM-DD"
                size="small"
                :clearable="false"
              />
              <ElInput
                v-model="detailDailog.newDatavalue"
                size="small"
                placeholder="在此填入数据"
              />
              <ElButton @click="detailDailog.showCreateNew = false" size="small">取消</ElButton>
              <ElButton
                type="primary"
                size="small"
                :loading="detailDailog.newCreateLoading"
                @click="toSaveNewRow"
                >保存</ElButton
              >
            </ElSpace>
          </div>
        </div>
      </template>
      <ElTable
        class="table"
        v-loading="detailDailog.dataLoading"
        border
        strip
        :data="detailDailog.valueList"
      >
        <ElTableColumn prop="id" label="ID" width="100">
          <template #default="scope">
            <div class="edit-column" @click="toEditValueRow(scope.row)">
              <Icon class="edit-icon" icon="svg-icon:box-edit" />
              <div class="row-id">{{ scope.row.id }}</div>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="日期">
          <template #default="scope">
            <div v-if="scope.row.isEditing">
              <ElDatePicker
                v-model="scope.row.datadate"
                value-format="YYYY-MM-DD"
                :clearable="false"
              />
            </div>
            <div v-else>{{ scope.row.datadate }}</div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="数值">
          <template #default="scope">
            <div v-if="scope.row.isEditing">
              <ElInput v-model="scope.row.datavalue" value-format="YYYY-MM-DD" />
            </div>
            <div v-else>{{ scope.row.datavalue }}</div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="有效" width="70" align="center">
          <template #default="scope">
            <div v-if="scope.row.isEditing">
              <ElCheckbox v-model="scope.row.is_active">是</ElCheckbox>
            </div>
            <div v-else>
              <Icon v-if="scope.row.is_active" icon="svg-icon:dash-yes" />
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="操作" width="70">
          <template #default="scope">
            <div v-if="scope.row.isEditing">
              <ElButton type="primary" link @click="toSaveEditValueRow(scope.row)">保存</ElButton>
            </div>
            <div v-else>
              <ElButton type="danger" link @click="toDeleteValueRow">删除</ElButton>
            </div>
          </template>
        </ElTableColumn>
      </ElTable>
      <template #footer>
        <div class="footer-box">
          <ElPagination
            v-model:current-page="detailDailog.page"
            v-model:page-size="detailDailog.pageSize"
            background
            small
            layout="total,prev,pager,next,jumper"
            :total="detailDailog.totalCount"
            @current-change="diagTablePageChange"
          />
          <div class="time-box">
            <div>创建时间 {{ detailDailog.createTime }}</div>
            <div>最近更新 {{ detailDailog.updateTime }}</div>
          </div>
        </div>
      </template>
    </Dialog>
  </div>
</template>
<style scoped lang="less">
.page-view {
  .actions-box {
    margin-bottom: 5px;
    display: flex;
    justify-content: flex-end;
  }
  .table {
    .edit-column {
      display: flex;
      align-items: center;
      cursor: pointer;
      .edit-icon {
        margin-right: 5px;
      }
    }
    .index-name {
      &:hover {
        .action {
          opacity: 1;
        }
      }
      .action {
        float: right;
        cursor: pointer;
        font-size: 12px;
        color: #409eff;
        opacity: 0;
      }
    }
  }
  .page-box {
    margin-top: 5px;
  }
  .title-box {
    display: flex;
    align-items: center;
    .title-name {
      margin-right: 15px;
    }
  }
  .footer-box {
    display: flex;
    align-items: center;
    .time-box {
      margin-left: auto;
      font-size: 9px;
      color: #666;
    }
  }
}
</style>
